package org.black.phoneUtility.sms.reply.content.broadcastReceiver;

import java.util.ArrayList;

import org.black.phoneUtility.sms.reply.app.service.SmsReplyReplyService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class ReceiveSmsBroadcastReceiver extends BroadcastReceiver {
	private static final String LOG_TAG = ReceiveSmsBroadcastReceiver.class
			.getName();

	@Override
	public void onReceive(final Context context, final Intent intent) {
		Log.d(LOG_TAG, "Receive SMS.");
		final Bundle bundle = intent.getExtras();
		try {
			if (bundle != null) {
				new Thread(new Runnable() {

					@Override
					public void run() {
						Object[] pdusObjects = (Object[]) bundle.get("pdus");
						if (pdusObjects != null) {
							long currentTimeInMillis = System
									.currentTimeMillis();
							ArrayList<String> oiginatingAddresses = new ArrayList<String>();
							ArrayList<String> displayMessageBodys = new ArrayList<String>();
							ArrayList<String> inboxIds = new ArrayList<String>();
							for (Object object : pdusObjects) {
								SmsMessage currentMessage = SmsMessage
										.createFromPdu((byte[]) object);

								String originatingAddress = currentMessage
										.getDisplayOriginatingAddress();
								String displayMessageBody = currentMessage
										.getDisplayMessageBody();
								oiginatingAddresses.add(originatingAddress);
								long date_sent = currentMessage
										.getTimestampMillis();
								displayMessageBodys.add(displayMessageBody);
								Log.d(LOG_TAG, "oiginatingAddress: "
										+ originatingAddress
										+ ", displayMessageBody: "
										+ displayMessageBody);

								// Slow down, in order to make sure SMS message
								// has been
								// written to inbox
								try {
									Thread.sleep(1000l);
								} catch (InterruptedException e) {
									Log.e(LOG_TAG,
											"Fail to sleep 1000l milliseconds",
											e);
								}

								String[] projection = { "_id" };
								Cursor cursor = context
										.getContentResolver()
										.query(Uri.parse("content://sms/inbox"),
												projection,
												"address" + " = ? " + " AND "
														+ "date_sent" + " = ? ",
												new String[] {
														originatingAddress,
														String.valueOf(date_sent) },
												null);
								if (cursor != null
										&& cursor.moveToFirst() == true) {
									String inboxId = cursor.getString(cursor
											.getColumnIndex("_id"));
									inboxIds.add(inboxId);
									Log.i(LOG_TAG, "sms inbox id: " + inboxId);
									cursor.close();
								}

							}
							Intent replyMessageServiceIntent = new Intent(
									context, SmsReplyReplyService.class);
							Bundle arguments = new Bundle();
							arguments
									.putInt(SmsReplyReplyService.ARGUMENTS_NUMBERS_TYPE,
											SmsReplyReplyService.NUMBERS_TYPE_SMS);

							arguments.putStringArrayList(
									SmsReplyReplyService.ARGUMENTS_NUMBERS,
									oiginatingAddresses);

							arguments
									.putStringArrayList(
											SmsReplyReplyService.ARGUMENTS_SMS_MESSAGE_BODIES,
											displayMessageBodys);
							arguments
									.putStringArrayList(
											SmsReplyReplyService.ARGUMENTS_SMS_INBOX_IDS,
											inboxIds);
							arguments
									.putLong(
											SmsReplyReplyService.ARGUMENTS_CURRENT_DATE_TIME_IN_MILLISECONDS,
											currentTimeInMillis);
							replyMessageServiceIntent.putExtras(arguments);
							context.startService(replyMessageServiceIntent);
						}

					}
				}).start();
			}
		} catch (Throwable throwable) {
			Log.e(LOG_TAG, "Unknown Error.", throwable);
		}

	}
}
